package com.propertypoint.util;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class MultipartRequestHandler {

	 
 
    public static String uploadByApacheFileUpload(HttpServletRequest request, String path) throws IOException, ServletException{
 
         
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String filePath=path; 
        if(isMultipart){
 
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
 
            try {
 
                List<FileItem> items = upload.parseRequest(request);
 
                for(FileItem item:items){
                		String timeStamp=String.valueOf(System.currentTimeMillis());
                        String myfileName=timeStamp+".jpg";
                        File newFile=new File(filePath,myfileName);
                        try {
							item.write(newFile);
							return myfileName;
						} catch (Exception e) {
							e.printStackTrace();
						}
  
                }
 
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
 
    
}
